﻿using Core.Commer.MQ.Connection;
using Core.Entity.Commer.Entity;
using Core_MQ_Admin.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;

namespace Core_MQ_Admin.Controllers
{
    public class HomeController : Controller
    {
        private readonly ILogger<HomeController> _logger;
        private readonly RabbitMQConnection _rabbitMQ;
        private readonly GetMessageInfo _messageInfo;

        public HomeController(ILogger<HomeController> logger, RabbitMQConnection rabbitMQ, GetMessageInfo messageInfo)
        {
            _logger = logger;
            _rabbitMQ = rabbitMQ;
            _messageInfo = messageInfo;
        }

        public IActionResult Index()
        {
            return View();
        }


        #region RabbitMQ 普通模式

        /// <summary>
        /// 生产者
        /// </summary>
        /// <param name="messege"></param>
        /// <returns></returns>
        public IActionResult NormalSendMessege(string[] message)
        {
            string getmessage = GetMessageInfo(message);
            if (!getmessage.Any()) return NotFound(getmessage);

            MQConfiguration mQConfiguration = new MQConfiguration()
            {
                message = message,
                queuename = "NormalCode"
            };
            try
            {
                if (_rabbitMQ.RMQSendInfoMessege(mQConfiguration).Result)
                {
                    return NotFound("消息发送成功=》" + getmessage);
                }
            }
            catch (Exception ex)
            {
                return NotFound("消息发送失败=》" + ex);
            }
            return Ok();
        }

        /// <summary>
        /// 消费消息
        /// </summary>
        /// <returns></returns>
        public IActionResult NormalReceivingMessege()
        {
            MQConfiguration mQConfiguration = new MQConfiguration()
            {
                queuename = "NormalCode",
            };
            try
            {
                string getmessage = _rabbitMQ.MqReceivingInfoMessage(mQConfiguration);
                if (!getmessage.Any()) return NotFound("没有消费任何消息");
                return NotFound("（tutorial）普通模式已经成功消费了消息=>" + getmessage);
            }
            catch (Exception ex)
            {
                return NotFound("消息消费失败：" + ex);
            }
        }
        #endregion

        #region RabbitMQ 工作模式
        /// <summary>
        /// 工作模式 生产消息
        /// </summary>
        /// <param name="message">消息</param>
        /// <returns></returns>
        public IActionResult MqWorkWiteMessage(string[] message)
        {
            string getmessage = GetMessageInfo(message);

            if (!getmessage.Any() || getmessage.Length == 0 || getmessage == null)
                return NotFound("请输入消息");

            var isok = _rabbitMQ.WorkeSendMessege(new MQConfiguration()
            {
                message = message,
                queuename = "WorkSend_Queue"
            }).Result;

            if (isok)
                return NotFound("工作模式，消息发送成功=》" + getmessage);
            else
                return NotFound("工作模式，消息发送失败=》" + getmessage);
        }

        /// <summary>
        /// 工作模式：消息者
        /// </summary>
        /// <returns></returns>
        public IActionResult MqWorkeReceivingMessage()
        {
            MQConfiguration mQConfiguration = new MQConfiguration()
            {
                queuename = "WorkSend_Queue",
            };

            string getmessage = _rabbitMQ.WorkeReceivingMessage(mQConfiguration);

            if (!getmessage.Any())
                return NotFound("工作模式消息消费失败");

            return NotFound("工作模式成功消费消息=》" + getmessage);
        }
        #endregion

        #region 发布订阅模式
        /// <summary>
        /// 发布订阅模式 生产消息
        /// </summary>
        /// <param name="message">消息</param>
        /// <returns></returns>
        public IActionResult MqPublishSubscribeMessage(string[] message)
        {
            string getmessage = GetMessageInfo(message);

            if (!getmessage.Any()) return NotFound(getmessage);

            try
            {
                var isok = _rabbitMQ.PublishSubscribeSendMessege(new MQConfiguration()
                {
                    message = message,
                    exchangename = "Publish_Subscribe"
                }).Result;

                if (isok)
                {
                    return Content("发布订阅模式，消息发送成功=》" + _messageInfo.GetMessage(message));
                }
            }
            catch (Exception ex)
            {
                return Content("发布订阅模式，消息发送失败=》" + ex);
            }
            return Ok();
        }

        /// <summary>
        /// 发布订阅模式：消息者
        /// </summary>
        /// <returns></returns>
        public IActionResult MqPublishSubscribeReceivingMessage()
        {
            try
            {
                MQConfiguration mQConfiguration = new MQConfiguration()
                {
                    exchangename = "Publish_Subscribe",
                };
                _rabbitMQ.PublishSubscribeReceivingMessage(mQConfiguration);
            }
            catch (Exception ex)
            {
                return Content("发布订阅模式，消息发送失败=》" + ex);
            }
            return Ok();
        }
        #endregion

        #region 路由模式 Routing
        public IActionResult MqRoutingMessage(string[] message)
        {
            string massageinfo = GetMessageInfo(message);

            if (!massageinfo.Any()) return NotFound(massageinfo);

            var isok = _rabbitMQ.MQRoutingSenMessage(new MQConfiguration()
            {
                message = message,
                routingKey = (message.Length > 0) ? message[0] : "routingKeyInfor",
                exchangename = "direct_logs",
                queuename = "Routing模式"
            });
            if (isok)
            {
                Console.WriteLine("路由模式消息发送成功=》" + _messageInfo.GetMessage(message));
            }
            return Ok();
        }

        public IActionResult MqRoutingRealinMessage(string[] args)
        {
            string infomation = GetMessageInfo(args);

            if (!infomation.Any()) return Content(infomation);

            try
            {
                MQConfiguration mQConfiguration = new MQConfiguration()
                {
                    exchangename = "direct_logs",
                    routingKey = (args.Length > 0) ? args[0] : "routingKeyInfor",
                    message = args


                };
                _rabbitMQ.MQRoutingReceivingMessage(mQConfiguration);
            }
            catch (Exception ex)
            {
                return Content("路由模式消息接收失败=》" + ex);
            }

            return Ok();
        }
        #endregion


        #region 通配符模式 发送消息
        public IActionResult MQWildcardSenMessages(string[] message)
        {
            string info = GetMessageInfo(message);

            if (!info.Any()) return Content(info);
            try
            {

                bool result = _rabbitMQ.MQWildcardSenMessage(new MQConfiguration()
                {
                    exchangename = "topic_logs",
                    routingKey="Topic_RoutingKey",
                    message = message,

                });

                if (!result)
                    return Content("通配符模式消息发送失败");
                else
                    return Content("消息发送成功");
            }
            catch (Exception ex)
            {
                return Content("通配符消息发送失败，失败原因为=》" + ex);
            }
        }
        #endregion
        #region MyRegion
        public IActionResult Privacy()
        {
            return View();
        }

        [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
        public IActionResult Error()
        {
            return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
        }
        #endregion


        /// <summary>
        /// 获取发送的消息
        /// </summary>
        /// <param name="message">消息体</param>
        /// <returns></returns>
        public string GetMessageInfo(string[] message)
        {
            string infomessage = string.Empty;

            infomessage = _messageInfo.GetMessage(message);

            if (!infomessage.Any() || infomessage.Length == 0 || infomessage == null)
                return infomessage = "请输入消息";
            else
                return infomessage;
        }
    }
}
